package com.cee.admin.config.converter;


import com.cee.common.constant.DateRegexEnum;
import com.cee.common.utils.TimeUtils;
import com.cee.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;


/**
 * @author wsz
 * @create 2023/3/9
 */
@Slf4j
public class LocalDateConverter implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(String source) {
        if (!StringUtils.hasText(source)) {
            return null;
        }
        for (DateRegexEnum timePattern : DateRegexEnum.values()) {
            if (source.matches(timePattern.getRegex())) {
                return TimeUtils.parseLocalDate(source, timePattern.getFormatter());
            }
        }
        log.error("字符串格式化成LocalDate失败，字符串：{}", source);
        throw new GlobalException("时间格式化失败");
    }
}
